package com.example.prodect.service.impl;

import com.example.prodect.dataObject.ProductInfo;
import com.example.prodect.dto.CartDTO;
import com.example.prodect.enums.ProductStatusEnum;
import com.example.prodect.enums.ResultEnum;
import com.example.prodect.exeception.ProductExeception;
import com.example.prodect.repository.ProductInfoRepository;
import com.example.prodect.service.ProductService;
import com.example.util.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.tools.json.JSONUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductInfoRepository productInfoRepository;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public List<ProductInfo> findUpList() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public List<ProductInfo> findByProductIdIn(List<String> list) {
        return productInfoRepository.findByProductIdIn(list);
    }

    @Override
    public void decreaseStock(List<CartDTO> list) {
        List<ProductInfo> productInfos = this.decreaseStockProcess(list);
        String json = JsonUtils.toJson(productInfos);
        //发送mq msg
                amqpTemplate.convertAndSend("productInfo",json);
    }

    /**
     * 扣库存
     * @param list
     * @return
     */
    @Transactional
    public List<ProductInfo> decreaseStockProcess(List<CartDTO> list) {
        List<ProductInfo> prolist = new ArrayList<>();
        for (CartDTO dto : list) {
            Optional<ProductInfo> one = productInfoRepository.findById(dto.getProductId());
            if (!one.isPresent()) {
                throw new ProductExeception(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer result = one.get().getProductStock() - dto.getProductQuantity();
            if (result < 0) {
                throw new ProductExeception(ResultEnum.PRODUCT_STCCK_ERROR);
            }
            one.get().setProductStock(result);
            productInfoRepository.save(one.get());
            prolist.add(one.get());
        }
        return prolist;
    }
}
